import subprocess
import logging


def m3u8_to_mp4(m3u8Path, mp4Path):
    # 构建安全的命令参数列表
    args = [
        'ffmpeg',
        '-allowed_extensions', 'ALL',
        '-protocol_whitelist', 'file,http,crypto,tcp',
        '-i', m3u8Path,
        '-c', 'copy',
        mp4Path
    ]
    logging.info('=== ffmpeg开始转码 ===')
    logging.info(f'm3u8路径： {m3u8Path}')
    logging.info(f'输出mp4路径： {mp4Path}')

    try:
        # 使用subprocess调用FFmpeg并捕获输出
        process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        stdout, stderr = process.communicate()
    except Exception as e:
        logging.error(f"启动ffmpeg失败：{e}")
        return False

    # 检查命令执行是否成功
    if process.returncode == 0:
        logging.info("=== ffmpeg转码完成 ====")
        logging.info(stdout.decode())
        return True
    else:
        logging.error("=== 转换失败！=== ")
        logging.error(stderr.decode())
        return False

# 示例用法
# m3 = '/path/to/your/m3u8/file.m3u8'
# m4 = '/path/to/output/mp4/file.mp4'
# m3u8_to_mp4(m3, m4)
